package com.yyp.car.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.yyp.car.Iservice.IUserService;
import com.yyp.car.model.User;
import com.yyp.exception.CarException;

@Controller
public class LoginController {
	@Resource(name = "userService")
	private IUserService userService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String loginGet() {
		return "login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String loginPost(String username,String password,HttpSession session) {
		/*
		 * User user = userService.login(username, password);
		session.setAttribute("user", user);
		if(user.getStudentMes()!=null)
		{
			return "redirect:/stIndex";
		}
		else if(user.getTeacherMes()!=null){
			return "redirect:/stIndex";
		}
		return "redirect:/back/index";*/
		
		Subject suser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username,password);
		token.setRememberMe(true);
		try {
			suser.login(token);
			User user=userService.findUser(username);
			session.setAttribute("user", user);
			if(user.getStatus()==1)
			{
				throw new CarException("对不起您已经被拉黑,请与管理员联系");
			}
			if(user.getStudentMes()!=null)
			{
				return "redirect:/stIndex";
			}
			else if(user.getTeacherMes()!=null){
				return "redirect:/stIndex";
			}
			return "redirect:/back/index";
		}catch (AuthenticationException e) {
			token.clear();
			throw new CarException("用户名或密码错误");
		}
	}
	
}
